<template>
  <div class="table-page">
    <div class="table-header">
      <h1>桌位管理</h1>
      <p>实时查看桌位状态，进行开台、清台、预定等操作</p>
    </div>

    <div class="table-container">
      <!-- 左侧区域选择 -->
      <div class="zone-selector">
        <el-tabs v-model="activeZone" @tab-click="handleZoneChange">
          <el-tab-pane label="A区" name="A" />
          <el-tab-pane label="B区" name="B" />
          <el-tab-pane label="C区" name="C" />
          <el-tab-pane label="D区" name="D" />
          <el-tab-pane label="E区" name="E" />
          <el-tab-pane label="F区" name="F" />
        </el-tabs>
      </div>

      <!-- 右侧桌位列表 -->
      <div class="table-list">
        <div class="table-grid">
          <div
            v-for="table in filteredTables"
            :key="table.id"
            class="table-card"
            :class="getTableStatusClass(table.status)"
            @click="selectTable(table)"
          >
            <div class="table-number">{{ table.number }}</div>
            <div class="table-capacity">
              <el-icon><User /></el-icon> {{ table.capacity }}人
            </div>
            <div class="table-status">{{ getTableStatusText(table.status) }}</div>
            <div v-if="table.status === 'occupied'" class="occupy-info">
              <el-icon><Clock /></el-icon> {{ table.occupyTime }}
            </div>
            <div v-if="table.orderInfo" class="order-info">
              <div class="order-no">订单: {{ table.orderInfo.orderNo }}</div>
              <div class="order-people">人数: {{ table.orderInfo.peopleCount }}人</div>
              <div class="order-amount">金额: ¥{{ table.orderInfo.totalAmount }}</div>
            </div>
          </div>
        </div>

        <!-- 状态说明 -->
        <div class="status-legend">
          <div class="legend-item">
            <span class="legend-color available"></span> 可用
          </div>
          <div class="legend-item">
            <span class="legend-color occupied"></span> 在用
          </div>
          <div class="legend-item">
            <span class="legend-color reserved"></span> 预定
          </div>
          <div class="legend-item">
            <span class="legend-color cleaning"></span> 清洁
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作面板 -->
    <div class="bottom-panel">
      <div class="panel-left">
        <div class="selected-table-info">
          <span v-if="selectedTable">
            已选桌位: <span class="table-num">{{ selectedTable.number }}</span> ({{ getTableStatusText(selectedTable.status) }})
          </span>
          <span v-else class="no-selection">请选择一个桌位进行操作</span>
        </div>
      </div>
      <div class="panel-right">
        <el-button
          type="primary"
          :disabled="!selectedTable || selectedTable.status !== 'available'"
          @click="openTable"
        >
          开台
        </el-button>
        <el-button
          type="success"
          :disabled="!selectedTable || selectedTable.status !== 'occupied'"
          @click="clearTable"
        >
          清台
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedTable || selectedTable.status !== 'available'"
          @click="reserveTable"
        >
          预定
        </el-button>
        <el-button
          type="info"
          :disabled="!selectedTable || selectedTable.status !== 'occupied'"
          @click="mergeTables"
        >
          并台
        </el-button>
        <el-button
          type="danger"
          :disabled="!selectedTable || selectedTable.status !== 'occupied'"
          @click="splitTable"
        >
          拆台
        </el-button>
        <el-button type="primary" size="small" @click="refreshTableData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 预定对话框 -->
    <el-dialog
      v-model="reservationDialogVisible"
      title="预定桌位"
      width="500px"
      :before-close="handleReservationDialogClose"
    >
      <el-form :model="reservationForm" ref="reservationFormRef" label-width="100px">
        <el-form-item label="桌号">
          <el-input v-model="reservationForm.tableNumber" disabled />
        </el-form-item>
        <el-form-item label="预定人姓名" prop="customerName">
          <el-input v-model="reservationForm.customerName" placeholder="请输入预定人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="reservationForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="预定时间" prop="reservationTime">
          <el-date-picker
            v-model="reservationForm.reservationTime"
            type="datetime"
            placeholder="选择预定日期和时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="人数" prop="numberOfGuests">
          <el-input-number v-model="reservationForm.numberOfGuests" :min="1" :max="selectedTable?.capacity" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="reservationForm.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleReservationDialogClose">取消</el-button>
          <el-button type="primary" @click="submitReservation">确定预定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, User, Clock } from '@element-plus/icons-vue'

const activeZone = ref('A')
const selectedTable = ref(null)
const reservationDialogVisible = ref(false)
const reservationFormRef = ref(null)
const reservationForm = reactive({
  tableNumber: '',
  customerName: '',
  contactPhone: '',
  reservationTime: '',
  numberOfGuests: 1,
  remark: ''
})

// 桌位数据
const tables = ref([
  { id: 1, number: 'A01', capacity: 4, status: 'available', zone: 'A', occupyTime: '' },
  { id: 2, number: 'A02', capacity: 6, status: 'occupied', zone: 'A', occupyTime: '09:30' },
  { id: 3, number: 'A03', capacity: 2, status: 'reserved', zone: 'A', occupyTime: '' },
  { id: 4, number: 'A04', capacity: 8, status: 'cleaning', zone: 'A', occupyTime: '' },
  { id: 5, number: 'A05', capacity: 4, status: 'available', zone: 'A', occupyTime: '' },
  { id: 6, number: 'A06', capacity: 6, status: 'available', zone: 'A', occupyTime: '' },
  { id: 7, number: 'B01', capacity: 4, status: 'available', zone: 'B', occupyTime: '' },
  { id: 8, number: 'B02', capacity: 6, status: 'occupied', zone: 'B', occupyTime: '10:00' },
  { id: 9, number: 'C01', capacity: 2, status: 'available', zone: 'C', occupyTime: '' },
  { id: 10, number: 'D01', capacity: 8, status: 'available', zone: 'D', occupyTime: '' },
  { id: 11, number: 'E01', capacity: 4, status: 'available', zone: 'E', occupyTime: '' },
  { id: 12, number: 'F01', capacity: 6, status: 'available', zone: 'F', occupyTime: '' }
])





// 从localStorage读取桌位状态和订单信息
const loadTableData = () => {
  try {
    // 读取桌位状态
    const savedTableStatus = localStorage.getItem('tableStatus')
    if (savedTableStatus) {
      const savedTables = JSON.parse(savedTableStatus)
      // 更新本地桌位数据
      tables.value.forEach(table => {
        const savedTable = savedTables.find(t => t.number === table.number)
        if (savedTable) {
          table.status = savedTable.status
          table.occupyTime = savedTable.occupyTime
        }
      })
    }

    // 读取订单信息
    const savedOrders = JSON.parse(localStorage.getItem('tableOrders') || '[]')
    savedOrders.forEach(order => {
      const table = tables.value.find(t => t.number === order.tableNumber)
      if (table) {
        table.orderInfo = {
          orderNo: order.orderNo,
          time: order.orderTime,
          peopleCount: order.peopleCount,
          totalAmount: order.totalAmount
        }
      }
    })
  } catch (error) {
    console.error('加载桌位数据失败:', error)
  }
}

const filteredTables = computed(() => {
  return tables.value.filter(table => table.zone === activeZone.value)
})

const handleZoneChange = () => {
  selectedTable.value = null // 切换区域时清空选中桌位
}

const getTableStatusClass = (status) => {
  return {
    'available': status === 'available',
    'occupied': status === 'occupied',
    'reserved': status === 'reserved',
    'cleaning': status === 'cleaning'
  }
}

const getTableStatusText = (status) => {
  const statusMap = {
    'available': '可用',
    'occupied': '在用',
    'reserved': '预定',
    'cleaning': '清洁中'
  }
  return statusMap[status] || '未知'
}

const selectTable = (table) => {
  selectedTable.value = table
}

const openTable = () => {
  if (selectedTable.value && selectedTable.value.status === 'available') {
    ElMessageBox.confirm(`确定要开台桌位 ${selectedTable.value.number} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      selectedTable.value.status = 'occupied'
      selectedTable.value.occupyTime = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      ElMessage.success(`${selectedTable.value.number} 已开台`)
    }).catch(() => {
      ElMessage.info('已取消开台')
    })
  }
}

const clearTable = () => {
  if (selectedTable.value && selectedTable.value.status === 'occupied') {
    ElMessageBox.confirm(`确定要清台桌位 ${selectedTable.value.number} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      selectedTable.value.status = 'cleaning'
      selectedTable.value.occupyTime = ''
      ElMessage.success(`${selectedTable.value.number} 已清台，进入清洁状态`)
      // 模拟清洁完成，一段时间后变为可用
      setTimeout(() => {
        if (selectedTable.value && selectedTable.value.number === selectedTable.value.number) {
          selectedTable.value.status = 'available'
          ElMessage.success(`${selectedTable.value.number} 清洁完成，已可用`)
        }
      }, 5000)
    }).catch(() => {
      ElMessage.info('已取消清台')
    })
  }
}

const reserveTable = () => {
  if (selectedTable.value && selectedTable.value.status === 'available') {
    reservationForm.tableNumber = selectedTable.value.number
    reservationForm.numberOfGuests = selectedTable.value.capacity
    reservationDialogVisible.value = true
  }
}

const handleReservationDialogClose = () => {
  reservationDialogVisible.value = false
  if (reservationFormRef.value) {
    reservationFormRef.value.resetFields()
  }
}

const submitReservation = async () => {
  if (!reservationFormRef.value) return
  await reservationFormRef.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(`确定为桌位 ${reservationForm.tableNumber} 预定吗？`, '确认预定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        const table = tables.value.find(t => t.number === reservationForm.tableNumber)
        if (table) {
          table.status = 'reserved'
          ElMessage.success(`桌位 ${reservationForm.tableNumber} 预定成功！`)
          handleReservationDialogClose()
        }
      }).catch(() => {
        ElMessage.info('已取消预定')
      })
    } else {
      ElMessage.error('请填写完整的预定信息！')
      return false
    }
  })
}

const mergeTables = () => {
  ElMessage.info('并台功能开发中')
}

const splitTable = () => {
  ElMessage.info('拆台功能开发中')
}

// 手动刷新桌位数据
const refreshTableData = () => {
  loadTableData()
  ElMessage.success('桌位数据已刷新')
}

onMounted(() => {
  // 初始化数据
  loadTableData()
  
  // 设置定时器，每5秒刷新一次桌位数据
  const timer = setInterval(() => {
    loadTableData()
  }, 5000)
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(timer)
  })
})
</script>

<style scoped>
.table-page {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-header {
  text-align: center;
  margin-bottom: 30px;
}

.table-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
}

.table-header p {
  font-size: 16px;
  color: #909399;
}

.table-container {
  flex: 1;
  display: flex;
  gap: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.zone-selector {
  width: 150px;
  border-right: 1px solid #e4e7ed;
  padding-right: 20px;
}

.table-list {
  flex: 1;
  overflow-y: auto;
}

.table-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
  padding-bottom: 20px;
}

.table-card {
  background: #f5f7fa;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 120px;
}

.table-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

.table-card.available {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.table-card.occupied {
  background-color: #fff0f6;
  border-color: #ffadd2;
}

.table-card.reserved {
  background-color: #fffbe6;
  border-color: #ffe58f;
}

.table-card.cleaning {
  background-color: #f0f2f5;
  border-color: #d9d9d9;
}

.table-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.table-capacity {
  font-size: 16px;
  color: #606266;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.table-status {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  color: #fff;
}

.table-card.available .table-status { background-color: #409EFF; }
.table-card.occupied .table-status { background-color: #F56C6C; }
.table-card.reserved .table-status { background-color: #E6A23C; }
.table-card.cleaning .table-status { background-color: #909399; }

.occupy-info {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.order-info {
  position: absolute;
  bottom: 8px;
  left: 8px;
  right: 8px;
  font-size: 10px;
  color: #606266;
  text-align: center;
  background: rgba(255, 255, 255, 0.9);
  padding: 4px;
  border-radius: 4px;
}

.order-no {
  font-weight: 600;
  margin-bottom: 2px;
}

.order-people,
.order-amount {
  margin-bottom: 2px;
}

.status-legend {
  display: flex;
  gap: 20px;
  margin-top: 20px;
  padding-top: 10px;
  border-top: 1px solid #e4e7ed;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.legend-color {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  margin-right: 8px;
  border: 1px solid #dcdfe6;
}

.legend-color.available { background-color: #e6f7ff; border-color: #91d5ff; }
.legend-color.occupied { background-color: #fff0f6; border-color: #ffadd2; }
.legend-color.reserved { background-color: #fffbe6; border-color: #ffe58f; }
.legend-color.cleaning { background-color: #f0f2f5; border-color: #d9d9d9; }

.bottom-panel {
  background: #fff;
  border-top: 1px solid #e4e7ed;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  margin-top: 20px;
}

.panel-left {
  font-size: 16px;
  color: #606266;
}

.selected-table-info .table-num {
  font-weight: bold;
  color: #303133;
  font-size: 18px;
}

.no-selection {
  color: #909399;
}

.panel-right .el-button {
  margin-left: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 